<?php
// +----------------------------------------------------------------------
// | CLTPHP.Pro [空控制器]
// +----------------------------------------------------------------------
// | Copyright (c) 2019-2029 https://www.cltphp.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://www.cltphp.com/detail-140.html )
// +----------------------------------------------------------------------
// | Author: chichu <1109305987@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;
use app\admin\model\Tags;
class EmptyController extends Base
{
    protected $table, $model,$modelid, $fields, $category;

    public function initialize()
    {
        parent::initialize();
        //当前表
        $this->table = strtolower(Request::controller());
        //模型ID
        $model = $this->get_model();
        $this->modelid = $model[$this->table];

        $this->model = Db::name('model')->where('id',$this->modelid)->find();
        //模型字段
        $this->fields = Db::name('field')->order('sort')->where('modelid', $this->modelid)->column('*', 'field');
        foreach ($this->fields as $key => $res) {
            $res['setup'] = string2array($res['setup']);
            $this->fields[$key] = $res;
        }
        //分类初始
        $this->category = $this->get_this_category();
    }

    public function index()
    {
        if (Request::isAjax()) {
            $catId = input('param.catid');
            $keyword = input('post.key');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $sort_by = input('sort_by') ? input('sort_by') : 'sort';
            $sort_order = input('sort_order') ? input('sort_order') : 'asc';
            $order = $sort_by . " " . $sort_order.',id desc';
            //获取分类详情
            $cinfo = Db::name('category')->where('id', $catId)->field('catdir,is_show,arrchildid')->find();

            //获取分类子集
            $catIds = $cinfo['arrchildid'];

            if (!empty($keyword)) {
                $map[] = array('title', 'like', '%' . $keyword . '%');
            }
            $prefix = config('database.connections.mysql.prefix');

            $Fields = Db::getTableFields($prefix . $this->table);
            if (in_array('catid', $Fields)) {
                $map[] = array('catid', 'in', $catIds);
            }

            $list = Db::name($this->table)
                ->where($map)
                ->order($order)
                ->paginate(array('list_rows' => $pageSize, 'page' => $page))
                ->toArray();
            $lists = $list['data'];
            foreach ($lists as $k => $v) {
                $lists[$k]['createtime'] = date('Y-m-d H:i:s', $v['createtime']);
                $lists[$k]['push_time'] = date('Y-m-d H:i:s', $v['push_time']);
                $lists[$k]['catdir'] = $cinfo['catdir'];
                $lists[$k]['is_show'] = $cinfo['is_show'];
                $lists[$k]['url'] = '/home/' . $cinfo['catdir'] . '/'.$v['id'].'html';//根据路由改动
            }
            return ['code' => 0, 'msg' => "获取成功", 'data' => $lists, 'count' => $list['total'], 'rel' => 1];
        } else {
            return view('content/index');
        }
    }

    //初始化添加页面
    public function add()
    {
        $form = new \Form();
        $view = [
            'form' => $form,
            'fields' => $this->fields,
            'info' => null,
            'action' => Request::action()
        ];
        return view('content/form', $view);
    }

    //添加
    public function insert()
    {
        $fields = $this->fields;
        Db::startTrans();
        try {
            $data = $this->checkfield($fields, Request::except(['file'], 'post'));
            if (isset($data['code']) && $data['code'] == 1) {
                return $data;
            }
            $time = time();
            $data['createtime'] = $time;
            $data['updatetime'] = $time;

            $data['userid'] = session('admin.id');
            $data['username'] = session('admin.username');

            $title_style = '';
            if (isset($data['style_color'])) {
                $title_style .= 'color:' . $data['style_color'] . ';';
                unset($data['style_color']);
            } else {
                $title_style .= 'color:#222;';
            }
            if (isset($data['style_bold'])) {
                $title_style .= 'font-weight:' . $data['style_bold'] . ';';
                unset($data['style_bold']);
            } else {
                $title_style .= 'font-weight:normal;';
            }
            if ($fields['title']['setup']['style'] == 1) {
                $data['title_style'] = $title_style;
                $content['title_style'] = $title_style;
            }
            if(isset($data['thumb'])){
                $content['thumb'] = $data['thumb'];
            }
            if(isset($data['push_time'])){
                $content['push_time'] = $data['push_time'];
            }
            if(isset($data['status'])){
                $content['status'] = $data['status'];
            }

            unset($data['style_color']);
            unset($data['style_bold']);
            unset($data['aid']);
            unset($data['aids']);
            unset($data['pics_name']);
            //编辑多图和多文件(多文件预留)
            foreach ($fields as $k => $v) {
                if ($v['type'] == 'files') {
                    if (!$data[$k]) {
                        $data[$k] = '';
                    }
                    $data[$v['field']] = $data['images'];
                }
                if ($v['type'] == 'images') {
                    if (isset($data[$k])) {
                        if (!$data[$k]) {
                            $data[$k] = '';
                        }
                    } else {
                        $data[$k] = '';
                    }
                    if ($data[$k]) {
                        $data[$v['field']] = json_encode($data[$k]);
                    }
                }
            }

            if($this->model['is_page']!=1){
                $content['title'] = $data['title'];
                $content['createtime'] = $time;
                $content['updatetime'] = $time;
                $content['catid'] = $data['catid'];
                $data['id'] = Db::name('content')->insertGetId($content);
            }
            $id = Db::name($this->table)->insertGetId($data);
            $aid = input('aid');
            if ($aid) {
                foreach ($aid as $k => $v) {
                    setAttachment($this->table, $k, $v, $id);
                }
            }
            //多图
            $adis = input('aids');
            if ($adis) {
                foreach ($adis as $key => $val) {
                    foreach ($val as $k1 => $v1) {
                        setAttachmentMore($this->table, $adis, $id);
                    }
                }
            }

            if(array_key_exists('tag',$fields)){
                if (!empty($data[$fields['tag']['field']])) {
                    Tags::where('model_id', $this->modelid)
                        ->where('id', 'IN', $data[$fields['tag']['field']])
                        ->inc('num')
                        ->update();
                }
            }
            // 提交事务
            Db::commit();
            return ['code' => 0, 'msg' => '添加成功！'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => 1, 'msg' => $e->getMessage()];
            //return ['code' => 1, 'msg' => '添加失败！'];
        }


    }

    //字段值修改
    public function cf()
    {
        $data = input('post.');
        $result = Db::name($this->table)->update($data);
        if ($result) {
            return ['code' => 0, 'msg' => '修改成功'];
        } else {
            return ['code' => 1, 'msg' => '修改失败'];
        }
    }

    public function edit()
    {
        $fields = $this->fields;
        $id = input('id');
        if ($this->model['is_page'] == 1) {
            $p = Db::name($this->table)->where('id', $id)->find();
            if (empty($p)) {
                $data['id'] = $id;
                $data['title'] = $this->category[$id]['catname'];
                $data['keywords'] = $this->category[$id]['keywords'];
                Db::name($this->table)->insert($data);
            }
        }
        $info = Db::name($this->table)->where('id', $id)->find();
        foreach ($fields as $k => $v) {
            if (array_key_exists($v['field'], $info)) {
                if ($info[$v['field']]) {
                    if ($v['type'] == 'images') {
                        $info[$v['field']] = json_decode($info[$v['field']], true);
                    } else if ($v['type'] == 'tag') {
                        //转换成文字
                        $tagStrArr = Tags::where('id', 'IN', $info[$v['field']])->column('name', 'id');
                        $tagStrs = '';
                        foreach ($tagStrArr as $tagStr) {
                            $tagStrs .= $tagStr . ',';
                        }
                        //去除右侧多余逗号
                        $info[$v['field']] = rtrim($tagStrs, ',');
                    }
                }
            }
        }

        $form = new \Form($info);
        $view = [
            'form' => $form,
            'fields' => $this->fields,
            'info' => $info,
            'action' => Request::action()
        ];
        return view('content/form', $view);
    }

    function update(){
        Db::startTrans();
        try {
            $fields = $this->fields;
            $data = $this->checkfield($fields, Request::except(['file'],'post'));
            if (isset($data['code'])) {
                return ['code' => 1, 'msg' => $data['msg']];
            }
            $data['userid'] = session('admin.id');
            $time = time();
            $data['updatetime'] = $time;
            $title_style = '';
            if (isset($data['style_color']) && $data['style_color']) {
                $title_style .= 'color:' . $data['style_color'] . ';';
                unset($data['style_color']);
            }
            if (isset($data['style_bold'])) {
                $title_style .= 'font-weight:' . $data['style_bold'] . ';';
                unset($data['style_bold']);
            }
            if ($fields['title']['setup']['style'] == 1) {
                $data['title_style'] = $title_style;
                $content['title_style'] = $title_style;
            }
            if(isset($data['thumb'])){
                $content['thumb'] = $data['thumb'];
            }
            if(isset($data['push_time'])){
                $content['push_time'] = $data['push_time'];
            }
            if(isset($data['status'])){
                $content['status'] = $data['status'];
            }
            unset($data['aid']);
            unset($data['pics_name']);
            //编辑多图和多文件
            foreach ($fields as $k => $v) {
                if ($v['type'] == 'images') {
                    if (!isset($data[$k])) {
                        $data[$k] = '';
                        $diff1 = Db::name('attimg')->where(['table' => $this->table, 'fid' => $data['id'], 'field' => $k])->column('aid');
                        Db::name('attimg')->where([['table', '=', $this->table], ['fid', '=', $data['id']], ['field', '=', $k]])->delete();
                        Db::name('attachment')->where('id', 'in', $diff1)->dec('count')->update();
                    }else{
                        $data[$v['field']] = json_encode($data[$k]);
                        $adis = input('aids');
                        setAttachmentMore($this->table, $adis, $data['id']);
                    }
                }
            }
            if($this->model['is_page']!=1){
                $content['title'] = $data['title'];
                $content['updatetime'] = $time;
                $content['catid'] = $data['catid'];
                Db::name('content')->where('id',$data['id'])->update($content);
            }
            Db::name($this->table)->strict(false)->update($data);
            //单张图片
            $aid = input('aid');
            if ($aid) {
                foreach ($aid as $k => $v) {
                    setAttachment($this->table, $k, $v, $data['id']);
                }
            }
            if (isset($data['tag_old'])) {
                $tagOld = $data['tag_old'];
                //删除标签扩展表
                if (!empty($tagOld)) {
                    Tags::where('model_id', $this->modelid)
                        ->where('id', 'IN', $tagOld)
                        ->dec('num')
                        ->update();
                }
            }
            if(array_key_exists('tag',$fields)){
                if (!empty($data[$fields['tag']['field']])) {
                    $tags = $data[$fields['tag']['field']];
                    Tags::where('model_id', $this->modelid)
                        ->where('id', 'IN', $tags)
                        ->inc('num')
                        ->update();
                }
            }
            Db::commit();
            return ['code' => 0, 'msg' => '修改成功！'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            //return ['code' => 1, 'msg' => '修改失败!'];
            return ['code' => 1, 'msg' => $e->getMessage()];
        }
    }

    function checkfield($fields, $post)
    {
        foreach ($post as $key => $val) {
            if (array_key_exists($key, $fields)) {
                if($fields[$key]['status']!=1){
                    continue;
                }
                $setup = $fields[$key]['setup'];
                if (!empty($fields[$key]['required']) && empty($val)) {
                    $result['msg'] = $fields[$key]['errormsg'] ? $fields[$key]['errormsg'] : $fields[$key]['name'].'为必填项！';
                    $result['code'] = 1;
                    return $result;
                }

                $minlength = $fields[$key]['minlength'];
                $maxlength = $fields[$key]['maxlength'];
                $length = strlen($val);
                //判断长度是否合法
                if ($maxlength && !($length >= $minlength && $length <= $maxlength)) {
                    $result['msg'] = $fields[$key]['name'].'长度超限：' . $minlength.'-'.$maxlength;
                    $result['code'] = 1;
                    return $result;
                }

                if (isset($setup['multiple'])) {
                    if (is_array($post[$key])) {
                        $post[$key] = implode(',', $post[$key]);
                    }
                }
                if (isset($setup['inputtype'])) {
                    if ($setup['inputtype'] == 'checkbox') {
                        $post[$key] = implode(',', $post[$key]);
                    }
                }
                if (isset($setup['fieldtype'])) {
                    if ($fields[$key]['type'] == 'checkbox') {
                        $post[$key] = implode(',', $post[$key]);
                    }
                }
                if ($fields[$key]['type'] == 'datetime') {
                    $post[$key] = strtotime($post[$key]);
                }
                elseif ($fields[$key]['type'] == 'textarea') {
                    $post[$key] = addslashes($post[$key]);
                }
                elseif ($fields[$key]['type'] == 'linkage') {
                    if ($post[$key][0]) {
                        $post[$key] = implode(',', $post[$key]);
                    } else {
                        unset($post[$key]);
                    }
                }
                elseif ($fields[$key]['type'] == 'editor') {
                    if (isset($post['description']) && $post['description'] == '' && isset($post['content'])) {
                        $content = stripslashes($post['content']);
                        $description_length = 120;
                        $post['description'] = getWords($content,$description_length);

                    }
                    if (isset($post['thumb']) && $post['thumb'] == '' && isset($post['content'])) {
                        $content = stripslashes($post['content']);
                        if (preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) {
                            $post['thumb'] = $matches[3][0];
                        }
                    }
                }
                elseif($fields[$key]['type'] == 'tag'){
                    if(array_key_exists('id', $post)){
                        $post['tag_old'] = Db::name($this->table)->where('id', $post['id'])->value($key);
                    }
                    //判断标签表是否存在，不存在则创建标签
                    $tagStr = $val;
                    if (!empty($tagStr)) {
                        $tagArr = explode(',', $tagStr);
                        $post[$key] = '';
                        foreach ($tagArr as $tag) {
                            //判断是否已存在该标签
                            $tagModule = Tags::where('name', $tag)->where('model_id', $this->modelid)->find();
                            if (!$tagModule) {
                                //新增该标签
                                $tagModuleId = Tags::insertGetId(['name' => $tag, 'num' => 0, 'model_id' => $this->modelid]);
                                $post[$key] .= $tagModuleId . ',';
                            } else {
                                //已存在的标签则获取标签ID
                                $tagId = Tags::where('name', $tag)->where('model_id', $this->modelid)->value('id');
                                $post[$key] .= $tagId . ',';
                            }
                        }
                        $post[$key] = rtrim($post[$key], ',');
                    }
                }
            }
        }
        return $post;
    }

    //删除
    public function del($ids)
    {
        Db::startTrans();
        try {
            Db::name($this->table)->delete($ids);
            Db::name('content')->delete($ids);
            delAttachment($this->table,$ids);
            Db::commit();
            return ['code' => 0, 'msg' => '删除成功！'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code' => 1, 'msg' => '删除失败!'];
        }
    }

    public function delImg()
    {
        if (!input('post.url')) {
            return ['code' => 0, '请指定要删除的图片资源'];
        }
        $file = public_path() . input('post.url');
        if (file_exists($file) && trim(input('post.url')) != '') {
            is_dir($file) ? deleteDir($file) : unlink($file);
        }
        if (input('post.id')) {
            $picurl = input('post.picurl');
            $picurlArr = explode(':', $picurl);
            $pics = substr(implode(":::", $picurlArr), 0, -3);
            Db::name($this->table)->where('id',input('post.id'))->update(array('pics' => $pics));
        }
        $result['msg'] = '删除成功!';
        $result['code'] = 1;
        return $result;
    }

    public function getRegion()
    {
        $list = Db::name('region')->where('pid',input("pid"))->select();
        return $list;
    }

    //初始分类
    public function get_this_category()
    {
        $list = Db::name('category')->order('sort')->select()->toArray();
        $pkid = Db::name('category')->getPk();
        $data = array();
        foreach ($list as $key => $val) {
            $data [$val [$pkid]] = $val;
        }
        return $data;
    }

    //初始模型
    function get_model()
    {
        $list = Db::name('model')->order('sort')->select();
        $pkid = Db::name('model')->getPk ();
        $data = array();
        foreach ($list as $key => $val) {
            $data[$val['name']] =  $val [$pkid];
        }
        return $data;
    }
}